package com.zbkj.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.client.config.SSESessionManager;
import com.zbkj.client.service.AgentClientService;
import com.zbkj.client.service.ClientLoginService;
import com.zbkj.client.service.MessageService;
import com.zbkj.client.service.VideoServiceCommon;
import com.zbkj.common.model.client.agent.*;
import com.zbkj.service.service.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理客户端服务实现类
 * 用于处理与外部AI代理的通信
 */
@Slf4j
@Service
public class AgentClientServiceImpl implements AgentClientService {

    @Autowired
    private VideoServiceCommon videoServiceCommon;

    @Autowired
    private UserLocationService userlocationservice;

    @Autowired
    private WeekTaskService weekTaskService;

    @Autowired
    private UserSpecialTopicCategoryService userSpecialTopicCategoryService;

    @Autowired
    private SpecialHotTopicService specialHotTopicService;

    @Autowired
    private SSESessionManager sseSessionManager;

    @Autowired
    private ContentCreateService contentCreateService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @Autowired
    private ClientLoginService clientLoginService;

    @Autowired
    private AgentService agentService;



    @Value("${workbench.agent}")
    private String agentBaseUrl;

    // 创作类型列表
    private static final List<String> categoryList = Arrays.asList(
            "情感共鸣类", "观点输出类", "吐槽互动类", "知识科普类", 
            "故事分享类", "回忆怀旧类", "群体认同类", "⼼声代⾔类"
    );

    /**
     * 用户位置代理API
     * 发送消息到位置相关的AI代理服务
     * 
     * @param message 用户消息
     * @return 代理响应结果
     */
    @Override
    public Map<String , Object> userLocationAgentApi(String message) {
        // JSON字符串
        String jsonString = "{\n" +
                "  \"user\": {\n" +
                "    \"profile\": {\n" +
                "      \"industry\": \"String\",\n" +
                "      \"sub_industry\": \"String\",\n" +
                "      \"region\": \"String\"\n" +
                "    },\n" +
                "    \"target_audience\": {\n" +
                "      \"demographic_profile\": \"String\",\n" +
                "      \"income_bracket\": \"String\",\n" +
                "      \"occupation_type\": \"String\",\n" +
                "      \"location_type\": \"String\",\n" +
                "      \"lifestyle\": \"String\",\n" +
                "      \"primary_concerns\": [\n" +
                "        \"String\"\n" +
                "      ],\n" +
                "      \"needs_analysis\": {\n" +
                "        \"explicit_needs\": [\n" +
                "          \"String\"\n" +
                "        ],\n" +
                "        \"implicit_needs\": [\n" +
                "          \"String\"\n" +
                "        ],\n" +
                "        \"emotional_needs\": [\n" +
                "          \"String\"\n" +
                "        ],\n" +
                "        \"value_based_needs\": [\n" +
                "          \"String\"\n" +
                "        ]\n" +
                "      }\n" +
                "    },\n" +
                "    \"marketing_needs\": {\n" +
                "      \"channel_preference\": [\n" +
                "        \"String\"\n" +
                "      ],\n" +
                "      \"content_focus\": [\n" +
                "        \"String\"\n" +
                "      ],\n" +
                "      \"brand_positioning\": \"String\",\n" +
                "      \"communication_style\": \"String\"\n" +
                "    }\n" +
                "  }\n" +
                "}";

        // 转换为Map
        JSONObject jsonObject = JSON.parseObject(jsonString);
        Map<String, Object> outputFormatMap = (Map<String, Object>) JSON.toJSON(jsonObject);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("outputFormat", outputFormatMap);

        List<String> instructions = new ArrayList<>();
        instructions.add("输出结构字段含义说明：user.profile.industry: 用户所属的主要行业类别（如：医疗健康、教育培训、电商零售等） user.profile.sub_industry: 行业内的细分领域（如：男性健康咨询、K12教育、跨境电商等） user.profile.region: 主要业务区域（如：一线城市、新一线城市、二三线城市、海外市场） user.target_audience.demographic_profile: 目标客户群体画像，包含年龄和性别等信息（如：28-45岁男性群体、30-40岁女性家长群体） user.target_audience.income_bracket: 目标客户收入水平（如：中低收入、中等收入、中高收入、高收入） user.target_audience.occupation_type: 目标客户职业类型（如：学生群体、白领管理层、蓝领工人、自由职业者） user.target_audience.location_type: 目标客户地理分布（如：一线城市、新一线城市、县城乡镇、线上业务全国覆盖等） user.target_audience.lifestyle: 目标客户生活方式特征（如：工作繁忙型、家庭导向型、娱乐消费型） user.target_audience.primary_concerns: 目标客户主要关注的问题或需求数组 user.target_audience.needs_analysis.explicit_needs: 显性需求数组 user.target_audience.needs_analysis.implicit_needs: 隐性需求数组 user.target_audience.needs_analysis.emotional_needs: 情感需求数组 user.target_audience.needs_analysis.value_based_needs: 人生理念和价值追求需求数组 user.marketing_needs.channel_preference: 偏好的营销推广渠道数组 user.marketing_needs.content_focus: 营销内容的重点方向数组 user.marketing_needs.brand_positioning: 期望的品牌形象定位字符串 user.marketing_needs.communication_style: 与客户沟通的风格偏好字符串");

        Map<String, Object> map = videoServiceCommon.agenticAgentApi(message, hashMap, instructions, null, null);
        log.info("返回的结构是：{}", map);
        if (map != null && map.get("msg") == null) {
            return (Map<String , Object>)map.get("result");
        }

        return map;

    }

    /**
     * 请求agent将返回的数据写入到用户定位表中
     * @param desc
     * @param message
     * @param userId
     * @param merId
     * @return
     */
    @Override
    public UserLocation insertUserLocation(String desc, String message, Integer userId, Integer merId){
        // 删除逻辑：根据本周日期范围和userId，将符合条件的记录标记为is_del=1
        boolean deleteResult = userlocationservice.lambdaUpdate()
                .eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getIsDel, 0)
                .set(UserLocation::getIsDel, 1)
                .update();

        Map<String, Object> map = userLocationAgentApi(message);


        //用户信息
        Map<String, Object> user = (Map<String, Object>)map.get("user");

        Map<String, Object> userProfile = (Map<String, Object>)user.get("profile");
        String industry = (String) userProfile.get("industry");
        String region = (String) userProfile.get("region");
        String subIndustry = (String) userProfile.get("sub_industry");

        //目标偏向
        Map<String, Object> targetAudience = (Map<String, Object>)user.get("target_audience");
        log.info("targetAudience的值是: {}", targetAudience);

        //营销推广
        Map<String, Object> marketingNeeds = (Map<String, Object>)user.get("marketing_needs");
        log.info("marketingNeeds的值是: {}", marketingNeeds);


        UserLocation userLocation = new UserLocation();
        userLocation.setUserId(userId);
        userLocation.setMerId(merId);

        //一句话描述
        userLocation.setLocationDesc(desc);

        //markdown返回的结果
        userLocation.setLocationResult(message);

        userLocation.setIndustry(industry);
        userLocation.setRegion(region);
        userLocation.setSubIndustry(subIndustry);
        userLocation.setTargetAudience(targetAudience);
        userLocation.setMarketingNeeds(marketingNeeds);

        boolean save = userlocationservice.save(userLocation);
        Integer id = userLocation.getId();

        //扣点
        clientLoginService.updateMerPoint(userId,
                merId,
                "userfix",
                id,
                getMouleName("userfix"),
                null,
                getPointByDuration("userfix", null),
                null
        );

        return userLocation;

    }

    /**
     * 子账号直接使用主账号的定位信息
     * @param id
     * @param userId
     * @return
     */
    @Override
    public UserLocation insertSubUserLocation(Integer id, Integer userId){
        // 删除逻辑：根据本周日期范围和userId，将符合条件的记录标记为is_del=1
        boolean deleteResult = userlocationservice.lambdaUpdate()
                .eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getIsDel, 0)
                .set(UserLocation::getIsDel, 1)
                .update();

        //获取主账号下的定位信息
        UserLocation userLocation = userlocationservice.getById(id);

        UserLocation subUserLocation = new UserLocation();
        subUserLocation.setUserId(userId);
        subUserLocation.setMerId(userLocation.getMerId());

        //一句话描述
        subUserLocation.setLocationDesc(userLocation.getLocationDesc());

        //markdown返回的结果
        subUserLocation.setLocationResult(userLocation.getLocationResult());

        subUserLocation.setIndustry(userLocation.getIndustry());
        subUserLocation.setRegion(userLocation.getRegion());
        subUserLocation.setSubIndustry(userLocation.getSubIndustry());
        subUserLocation.setTargetAudience(userLocation.getTargetAudience());
        subUserLocation.setMarketingNeeds(userLocation.getMarketingNeeds());

        boolean save = userlocationservice.save(subUserLocation);
        return subUserLocation;
    }

    /**
     * 用户位置代理API
     * 发送消息到位置相关的AI代理服务
     *
     * @param message 用户消息
     * @return 代理响应结果
     */
    @Override
    public Map<String , Object> weekTaskAgentApi(String message) {
        // JSON字符串
        String jsonString = "{\n" +
                "  \"first_week\": [\n" +
                "    {\n" +
                "      \"date\": \"String\",\n" +
                "      \"content_type\": \"String\",\n" +
                "      \"task_description\": \"String\",\n" +
                "      \"recommended_topic\": \"String\",\n" +
                "      \"target_audience\": \"String\",\n" +
                "      \"task_purpose\": \"String\",\n" +
                "      \"priority\": \"String\",\n" +
                "      \"creation_difficulty\": \"String\",\n" +
                "      \"content_attribute\": \"String\",\n" +
                "      \"strategy_focus\": \"String\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"date\": \"String\",\n" +
                "      \"content_type\": \"String\",\n" +
                "      \"task_description\": \"String\",\n" +
                "      \"recommended_topic\": \"String\",\n" +
                "      \"target_audience\": \"String\",\n" +
                "      \"task_purpose\": \"String\",\n" +
                "      \"priority\": \"String\",\n" +
                "      \"creation_difficulty\": \"String\",\n" +
                "      \"content_attribute\": \"String\",\n" +
                "      \"strategy_focus\": \"String\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        // 转换为Map
        JSONObject jsonObject = JSON.parseObject(jsonString);
        Map<String, Object> outputFormatMap = (Map<String, Object>) JSON.toJSON(jsonObject);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("outputFormat", outputFormatMap);

        List<String> instructions = new ArrayList<>();
        instructions.add("输出结构的字段含义： date: 具体创作日期，周一至周日标注 content_type: 具体创作内容，6字以内，如\"情感共鸣类\" task_description: 任务描述，具体创作内容，20字以内，简洁明确 recommended_topic: 推荐选题，具体选题建议 target_audience: 目标角色，内容针对的角色，具体到人群 task_purpose: 任务目的，创作意图和目标，明确创作目的 priority: 优先级，重要程度，高｜中 creation_difficulty: 创作难度，执行复杂度，简单/中等/复杂 content_attribute: 内容属性，营销属性分类，纯共鸣/软营销/硬营销 strategy_focus: 创作策略重点，从群体洞察、群体共鸣、价值提供等方向着手详细说明创作策略（35字以内）");

        Map<String, Object> map = videoServiceCommon.agenticAgentApi(message, hashMap, instructions, null, null);
        log.info("返回的结构是：{}", map);
        if (map != null && map.get("msg") == null) {
            return (Map<String , Object>)map.get("result");
        }

        return map;

    }

    /**
     * 请求agent将返回的数据写入到周任务表中
     * @param message 用户消息
     * @param userId 用户ID
     * @param merId 商户ID
     * @return 插入的记录ID列表
     */
    @Override
    public List<Integer> insertWeekTask(String message, Integer userId, Integer merId){
        // 每次先把之前生成的本周任务标记为删除状态
        Map<String, String> weekDates = getCurrentWeekDates();
        String mondayDate = weekDates.get("monday");
        String sundayDate = weekDates.get("sunday");
        
        log.info("准备删除本周任务，日期范围：{} 到 {}", mondayDate, sundayDate);
        
        // 删除逻辑：根据本周日期范围和userId，将符合条件的记录标记为is_del=1
        boolean deleteResult = weekTaskService.lambdaUpdate()
                .eq(WeekTask::getUserId, userId)
                .eq(WeekTask::getIsDel, 0)
                .ge(WeekTask::getDay, Date.valueOf(mondayDate))
                .le(WeekTask::getDay, Date.valueOf(sundayDate))
                .set(WeekTask::getIsDel, 1)
                .update();
        
        log.info("删除本周任务记录结果：{}", deleteResult);

        Map<String, Object> map = weekTaskAgentApi(message);
        List<Integer> insertedIds = new ArrayList<>();

        // 获取今天是周几和日期
        LocalDate today = LocalDate.now();
        String todayOfWeek = getDayOfWeekChinese(today.getDayOfWeek().getValue());
        String todayStr = today.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        
        log.info("今天是：{}，日期：{}", todayOfWeek, todayStr);

        // 获取第一周和第二周的数据
        List<Map<String, Object>> firstWeek = (List<Map<String, Object>>)map.get("first_week");
        List<Map<String, Object>> secondWeek = (List<Map<String, Object>>)map.get("second_week");

        // 计算本周的起始日期（周一）
        LocalDate weekStart = today.minusDays(today.getDayOfWeek().getValue() - 1);
        
        // 处理第一周数据
        if (firstWeek != null) {
            for (int i = 0; i < firstWeek.size(); i++) {
                Map<String, Object> taskData = firstWeek.get(i);
                WeekTask weekTask = createWeekTask(taskData, userId, merId, weekStart.plusDays(i), "first");
                weekTaskService.save(weekTask);
                insertedIds.add(weekTask.getId());
            }
        }

        // 处理第二周数据---先注释
//        if (secondWeek != null) {
//            LocalDate nextWeekStart = weekStart.plusDays(7);
//            for (int i = 0; i < secondWeek.size(); i++) {
//                Map<String, Object> taskData = secondWeek.get(i);
//                WeekTask weekTask = createWeekTask(taskData, userId, merId, nextWeekStart.plusDays(i), "second");
//                weekTaskService.save(weekTask);
//                insertedIds.add(weekTask.getId());
//            }
//        }

        log.info("成功插入{}条周任务记录", insertedIds.size());

        //每周任务扣点
        clientLoginService.updateMerPoint(userId,
                merId,
                "weektask",
                userId,
                getMouleName("weektask"),
                null,
                getPointByDuration("weektask", null),
                null
        );

        return insertedIds;
    }

    /**
     * 创建WeekTask对象
     */
    private WeekTask createWeekTask(Map<String, Object> taskData, Integer userId, Integer merId, 
                                   LocalDate date, String week) {
        WeekTask weekTask = new WeekTask();
        weekTask.setUserId(userId);
        weekTask.setMerId(merId);
        weekTask.setWeek(week);
        weekTask.setDay(Date.valueOf(date));
//        weekTask.setDayOfWeek(date.getDayOfWeek().getValue());
        weekTask.setDayOfWeek((String) taskData.get("date"));
        weekTask.setIsDel(0);
        
        // 设置任务相关字段
        weekTask.setContentType((String) taskData.get("content_type"));
        weekTask.setTaskDescription((String) taskData.get("task_description"));
        weekTask.setRecommendedTopic((String) taskData.get("recommended_topic"));
        weekTask.setTargetAudience((String) taskData.get("target_audience"));
        weekTask.setTaskPurpose((String) taskData.get("task_purpose"));
        weekTask.setStrategyFocus((String) taskData.get("strategy_focus"));
        weekTask.setContentAttribute((String) taskData.get("content_attribute"));
        
        // 设置优先级和难度
//        String priorityStr = (String) taskData.get("priority");
        weekTask.setPriority((String) taskData.get("priority"));
        
//        String difficultyStr = (String) taskData.get("creation_difficulty");
        weekTask.setCreationDifficulty((String) taskData.get("creation_difficulty"));
        
        return weekTask;
    }

    /**
     * 获取中文星期几
     */
    private String getDayOfWeekChinese(int dayOfWeek) {
        String[] weekDays = {"", "周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        return weekDays[dayOfWeek];
    }

    /**
     * 根据当前日期返回这周周一的日期和周日的日期
     * @return Map包含monday和sunday两个key，值为yyyy-MM-dd格式的日期字符串
     */
    @Override
    public Map<String, String> getCurrentWeekDates() {
        LocalDate today = LocalDate.now();
        
        // 计算本周周一（当前日期减去当前是周几的天数，再加1天）
        LocalDate monday = today.minusDays(today.getDayOfWeek().getValue() - 1);
        
        // 计算本周周日（周一加6天）
        LocalDate sunday = monday.plusDays(6);
        
        Map<String, String> weekDates = new HashMap<>();
        weekDates.put("monday", monday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        weekDates.put("sunday", sunday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        
        log.info("当前周日期范围：周一 {} 到周日 {}", weekDates.get("monday"), weekDates.get("sunday"));
        
        return weekDates;
    }

    /**
     * 创建热点榜单API
     * 发送消息到热点榜单创建的AI代理服务
     *
     * @param message 用户消息
     * @return 代理响应结果
     */
    @Override
    public Map<String, Object> createTopicApi(String message, Integer isMarketing, Map<String, Object> agentUserInfo) {
        // JSON字符串
        String jsonString = "{\n" +
                "  \"category\": \"String\",\n" +
                "  \"target_analysis\": \"String\",\n" +
                "  \"topics\": [\n" +
                "    {\n" +
                "      \"title\": \"String\",\n" +
                "      \"description\": \"String\",\n" +
                "      \"purpose\": \"String\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"strategy_notes\": \"String\"\n" +
                "}";

        // 转换为Map
        JSONObject jsonObject = JSON.parseObject(jsonString);
        Map<String, Object> outputFormatMap = (Map<String, Object>) JSON.toJSON(jsonObject);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("outputFormat", outputFormatMap);

        List<String> instructions = new ArrayList<>();

        String agentId = "";
        if(isMarketing == 1){
            agentId = "622d8641-168b-49f2-8be4-3fa8e21ad99f";
            //营销类的
            instructions.add("输出结构字段含义说明：category: 内容分类类型，固定为\"轻度营销类\" target_analysis: 目标群体深度分析，包括年龄段、职业特征、生活状态、心理特征、核心痛点等详细描述 topics: 选题列表数组，每个选题包含以下字段 topics[].title: 选题标题，需要具有吸引力和共鸣感，可包含轻度营销元素 topics[].description: 选题内容描述，简要说明选题的核心内容和表达方式 topics[].purpose: 选题目的，说明该选题希望达到的共鸣效果或营销转化价值 strategy_notes: 策略备注，说明整体选题策略、目标用户痛点、营销转化设计思路等");
        }else{
            //非营销类的
            agentId = "cdfbfb59-c721-4162-b8d8-0e745ad09b4d";
            instructions.add("输出结构字段含义说明：category: 内容分类类型，如\"情感共鸣类\"、\"观点输出类\"、\"吐槽互动类\"等 target_analysis: 目标群体深度分析，包括年龄段、职业特征、生活状态、心理特征、核心痛点等详细描述 topics: 选题列表数组，每个选题包含以下字段 topics[].title: 选题标题，需要具有吸引力和共鸣感，避免营销色彩 topics[].description: 选题内容描述，简要说明选题的核心内容和表达方式 topics[].purpose: 选题目的，说明该选题希望达到的共鸣效果或情感价值 strategy_notes: 策略备注，说明整体选题策略、目标用户痛点、共鸣设计思路等");
        }
        Map<String, Object> map = videoServiceCommon.agenticAgentApi(message, hashMap, instructions,agentId, agentUserInfo);
        log.info("返回的结构是：{}", map);
        if (map != null && map.get("msg") == null) {
            return (Map<String, Object>) map.get("result");
        }

        return map;
    }

    /**
     * 创建话题并保存到数据库
     * @param userId 用户ID
     * @param merId 商户ID
     * @return 插入的记录ID列表
     */
    @Override
    public List<Integer> createTopic(Integer userId, Integer merId, Map<String, Object> agentUserInfo) {
        boolean deleteResult = specialHotTopicService.lambdaUpdate()
                .eq(SpecialHotTopic::getUserId, userId)
                .eq(SpecialHotTopic::getIsDel, 0)
                .set(SpecialHotTopic::getIsDel, 1)
                .update();

        List<Integer> insertedIds = new ArrayList<>();
        
        try {
            // 1. 从categoryList中随机选择三个
            List<String> randomCategories = new ArrayList<>(categoryList);
            Collections.shuffle(randomCategories);
            List<String> selectedCategories = randomCategories.subList(0, 2);
            
            // 2. 添加"轻度营销类"
            selectedCategories.add("轻度营销类");
            
            log.info("选择的创作类型：{}", selectedCategories);
            
            // 3. 保存到用户选题类型表或者更新表
            UserSpecialTopicCategory userCategoryById = userSpecialTopicCategoryService.getByUserId(userId);
            Integer categoryId = 0;
            if (userCategoryById != null) {
                userCategoryById.setCategorys(selectedCategories);
                userSpecialTopicCategoryService.updateById(userCategoryById);
                categoryId = userCategoryById.getId();
                log.info("更新用户选题类型成功，ID：{}，创作类型:{}", userCategoryById.getId(), selectedCategories);
            }else{
                UserSpecialTopicCategory userCategory = new UserSpecialTopicCategory();
                userCategory.setCategorys(selectedCategories);
                userCategory.setUserId(userId);
                userCategory.setMerId(merId);
                userSpecialTopicCategoryService.save(userCategory);
                categoryId = userCategory.getId();
                log.info("保存用户选题类型成功，ID：{}，创作类型:{}", userCategory.getId(), selectedCategories);
            }

            // 4. 循环每个创作类型，调用createTopicApi
            for (String category : selectedCategories) {

                //循环调用创作话题的api，生成数据
                Map<String, Object> topicResult = new HashMap<>();
                if (category.equals("轻度营销类")){
                    topicResult = createTopicApi(category,1, agentUserInfo);
                }else{
                    topicResult = createTopicApi(category,0, agentUserInfo);
                }

                log.info("专业榜单返回的数据为：{}", topicResult);

                if (topicResult != null && !topicResult.isEmpty()) {
                    String categoryName = (String) topicResult.get("category");
                    String targetAnalysis = (String) topicResult.get("target_analysis");
                    List<Map<String, Object>> topics = (List<Map<String, Object>>) topicResult.get("topics");
                    
                    // 5. 保存话题到数据库
                    if (topics != null) {
                        for (Map<String, Object> topic : topics) {
                            SpecialHotTopic specialHotTopic = new SpecialHotTopic();
                            specialHotTopic.setCategory(categoryName);
                            specialHotTopic.setTargetAnalysis(targetAnalysis);
                            specialHotTopic.setTitle((String) topic.get("title"));
                            specialHotTopic.setDescription((String) topic.get("description"));
                            specialHotTopic.setPurpose((String) topic.get("purpose"));
                            specialHotTopic.setUserId(userId);
                            specialHotTopic.setMerId(merId);
                            
                            specialHotTopicService.save(specialHotTopic);
                            insertedIds.add(specialHotTopic.getId());
                            
                            log.info("保存话题成功，ID：{}，标题：{}", specialHotTopic.getId(), specialHotTopic.getTitle());
                        }
                    }
                }
            }
            
            log.info("成功创建{}个话题", insertedIds.size());

            //专业榜单扣点
            clientLoginService.updateMerPoint(userId,
                    merId,
                    "hot",
                    categoryId,
                    getMouleName("hot"),
                    null,
                    getPointByDuration("hot", null),
                    null
            );
            
        } catch (Exception e) {
            log.error("创建话题过程中发生错误", e);
        }
        
        return insertedIds;
    }

    /**
     * 流式聊天API
     * 发送消息到指定的AI代理服务并返回流式响应
     *
     * @param agentId AI代理ID
     * @param message 用户消息
     * @param sessionId SSE会话ID
     * @param agentUserInfo 代理用户信息
     * @param response HTTP响应对象
     */
    @Override
    public void chatStream(String agentId, String message, String sessionId, Map<String, Object> agentUserInfo, HttpServletResponse response, String method, Map<String, Object> params, String agentSessionId) {
        log.info("chatStream开始处理，agentId: {}, message: {}, sessionId: {}, method: {}", agentId, message, sessionId, method);

        // 设置SSE响应头
        response.setContentType("text/event-stream; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Cache-Control");

        try {
            String url = agentBaseUrl + "/api/v1/agents/" + agentId + "/chat/stream";
            log.info("开始请求外部API: {}", url);

            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(300000);

            try (OutputStream os = connection.getOutputStream()) {
                Map<String, Object> requestMap = new HashMap<>();
                requestMap.put("message", message);
                if (agentUserInfo != null) {
                    //用户信息可以传空
                    requestMap.put("user_info", agentUserInfo);
                }

                if (agentSessionId != null) {
                    //用户信息可以传空
                    requestMap.put("session_id", agentSessionId);
                }


                String jsonRequest = JSON.toJSONString(requestMap);
                os.write(jsonRequest.getBytes("UTF-8"));
                os.flush();
                log.info("已发送请求数据: {}", jsonRequest);
            }

            int responseCode = connection.getResponseCode();
            log.info("外部API响应码: {}", responseCode);

            if (responseCode != 200) {
                throw new RuntimeException("HTTP请求失败，状态码: " + responseCode);
            }


            String agentSessionIdRes = null;
            // 获取外部API返回的header中的x-session-id
            agentSessionIdRes = connection.getHeaderField("x-session-id");
            if (agentSessionIdRes != null) {
                log.info("外部API返回的x-session-id(agentSessionId): {}", agentSessionIdRes);
                // 你可以根据需要将agentSessionId传递到response header或params等
                response.setHeader("x-session-id", agentSessionIdRes);
                if (params != null) {
                    params.put("agentSessionId", agentSessionIdRes);
                }
            } else {
                log.info("外部API未返回x-session-id");
            }

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
                String line;
                int lineCount = 0;
                StringBuilder contentResult = new StringBuilder(); // 用于拼接完整的content内容

                while ((line = reader.readLine()) != null) {
                    lineCount++;
                    log.debug("接收到第{}行数据: {}", lineCount, line);

                    // 如果method不为空，需要将返回的流式数据插入数据库
                    if (method != null && !method.trim().isEmpty()) {
                        // 判断是否以"data: "开头
                        if (line.startsWith("data: ")) {
                            try {
                                String jsonData = line.substring(6); // 移除 'data: ' 前缀
                                JSONObject jsonObject = JSON.parseObject(jsonData);
                                
                                // 检查是否是delta事件
                                String event = jsonObject.getString("event");
                                if ("delta".equals(event)) {
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    if (data != null) {
                                        String content = data.getString("content");
                                        if (content != null) {
                                            contentResult.append(content);
                                            log.debug("提取到content内容: {}", content);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                log.warn("解析流式数据失败: {}", e.getMessage());
                            }
                        }
                    }

                    // 直接写入HTTP响应流，同时尝试通过SSE会话发送
                    response.getWriter().write(line + "\n");
                    response.getWriter().flush();

                    // 如果提供了sessionId，也尝试通过SSE会话发送
                    if (sessionId != null && !sessionId.isEmpty()) {
                        try {
                            boolean sent = sseSessionManager.sendRawToSession(sessionId, line + "\n");
                            if (sent) {
                                log.debug("SSE透传成功，sessionId: {}", sessionId);
                            } else {
                                log.warn("SSE透传失败，sessionId: {}", sessionId);
                            }
                        } catch (Exception e) {
                            log.warn("SSE透传异常，sessionId: {}, 错误: {}", sessionId, e.getMessage());
                        }
                    }
                }
                log.info("流式处理完成，共处理{}行数据", lineCount);

                //调用AI工具 扣点
                Map<String,Object> moduleMap = new HashMap<>();
                moduleMap.put("13abe95f-2b89-4333-a9de-69148fff5bf3", "contentCreate");//文案创作
                moduleMap.put("18148f52-3e06-4349-a9d1-bbc774ed3a53", "magicPen");//魔法笔
//                        moduleMap.put("8b44308c-5f29-4490-b7eb-46ca36ead41b", "userLocation");//用户定位,没点确定的

                if(moduleMap.get(agentId) != null) {
                    clientLoginService.updateMerPoint((Integer) params.get("userId"),
                            (Integer)params.get("merId"),
                            "agent",
                            0,
                            getMouleName((String) moduleMap.get(agentId)),
                            "",
                            getPointByDuration((String) moduleMap.get(agentId), null),
                            null
                    );
                }
                
                // 如果method不为空，调用对应的数据库插入方法
                if (method != null && !method.trim().isEmpty() && params != null) {
                    try {
                        // 将拼接的完整字符串放入params
                        params.put("contentResult", contentResult.toString());
                        log.info("准备调用数据库插入方法: {}, content长度: {}", method, contentResult.length());

                        // 根据method调用对应的数据库插入方法
                        if ("insertContentCreate".equals(method)) {
                            insertContentCreate(params);
                        } else if ("insertMessage".equals(method)) {
                            messageService.insertMessage(params);
                        } else {
                            log.warn("未知的数据库插入方法: {}", method);
                        }
                    } catch (Exception e) {
                        log.error("数据库插入失败，method: {}, 错误: {}", method, e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            log.error("chatStream处理失败", e);
            try {
                String errorMsg = "[ERROR] " + e.getMessage() + "\n";
                response.getWriter().write(errorMsg);
                response.getWriter().flush();

                // 如果提供了sessionId，也尝试通过SSE会话发送错误信息
                if (sessionId != null && !sessionId.isEmpty()) {
                    try {
                        sseSessionManager.sendRawToSession(sessionId, errorMsg);
                    } catch (Exception ignored) {}
                }
            } catch (Exception ignored) {}
        }
    }

    /**
     * 获取代理用户信息
     * 根据用户位置信息构建代理服务所需的用户信息参数
     *
     * @param userLocation 用户位置信息
     * @return 代理服务用户信息参数
     */
    @Override
    public Map<String, Object> getAgentUserInfo(UserLocation userLocation) {
        log.info("开始构建代理用户信息，用户ID: {}", userLocation.getUserId());
        
        // 2. 拼接user_info参数
        Map<String, Object> userInfoJson = new HashMap<>();
        Map<String, Object> userInfoRequestJson = new HashMap<>();
        Map<String, Object> userInfoProfileJson = new HashMap<>();
        
        userInfoProfileJson.put("industry", userLocation.getIndustry());
        userInfoProfileJson.put("sub_industry", userLocation.getSubIndustry());
        userInfoProfileJson.put("region", userLocation.getRegion());

        userInfoJson.put("profile", userInfoProfileJson);
        userInfoJson.put("marketing_needs", userLocation.getMarketingNeeds());
        userInfoJson.put("target_audience", userLocation.getTargetAudience());

        userInfoRequestJson.put("user", userInfoJson);

        log.info("代理用户信息构建完成: {}", userInfoRequestJson);
        return userInfoRequestJson;
    }

    /**
     * 插入文案创作记录
     * 根据传入的参数创建并保存ContentCreate记录
     *
     * @param params 包含文案创作相关参数的Map
     */
    private void insertContentCreate(Map<String, Object> params) {
        try {
            log.info("开始插入文案创作记录，参数: {}", params);
            ContentCreate contentCreate = new ContentCreate();
            
            // 设置基本信息
            contentCreate.setContent((String) params.get("message"));
            contentCreate.setContentCreateResult((String)params.get("contentResult"));
            contentCreate.setUserInfo((Map<String, Object>) params.get("userInfo"));
            contentCreate.setUserId((Integer) params.get("userId"));
            contentCreate.setMerId((Integer)params.get("merId"));
            contentCreate.setWeekTaskId((Integer)params.get("weekTaskId"));
            contentCreate.setThirdHotId((Integer)params.get("thirdHotId"));
            contentCreate.setHotTopicId((Integer)params.get("hotTopicId"));
            contentCreate.setRecommendTag((String)params.get("recommendTag"));
            contentCreate.setDescription((String)params.get("desc"));
            contentCreate.setSource((String)params.get("source"));
            
            // 保存到数据库
            boolean saveResult = contentCreateService.save(contentCreate);
            log.info("文案创作记录保存结果: {}, 记录ID: {}", saveResult, contentCreate.getId());
            
        } catch (Exception e) {
            log.error("插入文案创作记录失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 根据模块和时长获取需要扣的点数
     * @param module 模块名称
     * @param duration 时长（秒）
     * @return
     */
    @Override
    public Double getPointByDuration(String module, Integer duration) {
        if (module == null || module.trim().isEmpty()) {
            return 0.0;
        }

        Map<String, Double> costPointConfig = new HashMap<String, Double>();

        //每分钟扣点
        costPointConfig.put("videoSplit", 3.0);
        costPointConfig.put("videoSubtitle", 1.0);
        costPointConfig.put("addVoice", 1.0);
        costPointConfig.put("addVideo", 4.0);
        costPointConfig.put("picSearch", 1.0);
        costPointConfig.put("templateVideo", 2.0);

        //每次扣点
        costPointConfig.put("agent", 0.1);  //一次扣0.1
        costPointConfig.put("chat", 0.1);  //一次扣0.1
        costPointConfig.put("group", 0.1);  //一次扣0.1
        costPointConfig.put("userfix", 0.1);  //一次扣0.1
        costPointConfig.put("contentCreate", 0.1);  //一次扣0.1
        costPointConfig.put("subtitleAgent", 0.1); //一次扣0.1
        costPointConfig.put("weektask", 0.1);
        costPointConfig.put("magicPen", 0.1);
        costPointConfig.put("hot", 0.1);
        costPointConfig.put("userLocation", 0.1);
        costPointConfig.put("aiTitle", 0.1);

        Double result = 0.0;

        List<String> agentList =  Arrays.asList("agent", "group", "subtitleAgent",
                "userfix","contentCreate", "weektask", "magicPen", "hot", "userLocation", "aiTitle");

        if (agentList.contains(module)) {
            result = costPointConfig.get(module);
        }else{
            Double unitCost = costPointConfig.get(module);
            double rawResult = (duration * unitCost) / 60.0;
            // 保留一位小数并向上取整
            double temp = Math.ceil(rawResult * 10) / 10.0;
            result = temp;
        }

        return result;
    }

    /**
     * 根据模块和时长获取需要扣的点数
     * @param module 模块名称
     * @return
     */
    @Override
    public String getMouleName(String module) {

        Map<String, String> costPointConfig = new HashMap<>();
        costPointConfig.put("agent", "智能体");
        costPointConfig.put("chat", "AI对话");
        costPointConfig.put("group", "AI群组对话");
        costPointConfig.put("videoSplit", "视频拆解");
        costPointConfig.put("videoSubtitle", "视频转文案");
        costPointConfig.put("addVoice", "合成声音");
        costPointConfig.put("addVideo", "合成数字人视频");
        costPointConfig.put("subtitleAgent", "字幕处理");
        costPointConfig.put("picSearch", "素材搜索");
        costPointConfig.put("templateVideo", "视频剪辑");
        costPointConfig.put("weektask", "每日任务生成");
        costPointConfig.put("userfix", "商业定位");
        costPointConfig.put("contentCreate", "文案撰写");
        costPointConfig.put("magicPen", "魔法笔");
        costPointConfig.put("hot", "热榜榜单");
        costPointConfig.put("userLocation", "用户定位");
        costPointConfig.put("aiTitle", "AI生成标题");

        String result = costPointConfig.get(module);

        return result;
    }
} 